package com.ruoyi.web.controller.custom;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.from.CustomerDetailsExport;
import com.ruoyi.system.domain.from.CustomerDetailsInfoPage;
import com.ruoyi.system.domain.vo.CustomerDetailsPageVo;
import com.ruoyi.system.service.ICrmCustomerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/customerdetails/info")
@Api(value = "客户明细", tags = "客户明细")
@Slf4j
public class CustomerDetailsController {


    @Autowired
    private ICrmCustomerUserService iCrmCustomerUserService;

    /**
     * 查询意向客户明细列表
     */
    @ApiOperation(value = "查询客户明细列表", notes = "查询客户明细列表")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @PostMapping("/custom/details/{customerId}")
    @PreAuthorize("@ss.hasPermi('custom:info:detailList')")
    public R<CustomerDetailsPageVo> getContractedlist(@PathVariable Long customerId, @RequestBody CustomerDetailsInfoPage crmCustomerInfoPage) {
        return iCrmCustomerUserService.crmCustomerUserPage(customerId, crmCustomerInfoPage);
    }

    /**
     * 查询签约客户明细列表
     */
    @ApiOperation(value = "查询客户明细列表", notes = "查询客户明细列表")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @PostMapping("/customer/details/{customerId}")
    @PreAuthorize("@ss.hasPermi('contracted:info:detailList')")
    public R<CustomerDetailsPageVo> getCustomerlist(@PathVariable Long customerId, @RequestBody CustomerDetailsInfoPage crmCustomerInfoPage) {
        return iCrmCustomerUserService.crmCustomerUserPage(customerId, crmCustomerInfoPage);
    }

    /**
     * 删除详情中数据
     */
    @ApiOperation(value = "删除详情中数据", notes = "删除详情中数据")
    @ApiImplicitParam(name = "id", value = "详情ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @DeleteMapping("/customer/details/delete/{id}")
    @PreAuthorize("@ss.hasPermi('customer:info:detaildelete')")
    public R deleteDetailList(@PathVariable Long id) {
        return iCrmCustomerUserService.deleteCrmCustomerId(id);
    }

    /**
     * 导出客户列表
     */
    @ApiOperation(value = "全量导出客户详情列表", notes = "全量导出客户详情列表")
    @PostMapping("/export")
    public void export(@RequestBody CustomerDetailsExport customerDetailsExport, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            List<Map<String, String>> dataList = iCrmCustomerUserService.export(customerDetailsExport);
            File outputFile = new File("result.xlsx");
            EasyExcel.write(outputFile)
                    // 这里放入动态头
                    .head(getHeader(dataList,customerDetailsExport.getReptileType())).sheet("汇总表")
                    // 这里数据用 List<List<String>> 去传入
                    .doWrite(getData(dataList));
            // 导出
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename=export_data.xlsx");
            bis = new BufferedInputStream(new FileInputStream(outputFile));
            // 输出流
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
            }
        }
    }

    private static List<List<String>> getHeader(List<Map<String, String>> dataList,String reptileType) {
        List<List<String>> list = new ArrayList();
        Map<String, String> headerData = dataList.stream().findAny().orElse(new HashMap<>());
        if (reptileType.equals("eligible")){
            headerData.forEach((name, value) -> {
                List<String> header = new ArrayList<String>();
                if (name.equals("deptNumber")) {
                    header.add("单位编号");
                } else if (name.equals("userNumber")) {
                    header.add("个人编号");
                } else if (name.equals("userName")) {
                    header.add("姓名");
                } else if (name.equals("userIdentityCardNumber")) {
                    header.add("证件号码");
                }else if (name.equals("userAge")){
                    header.add("年龄");
                }else if (name.equals("userGender")){
                    header.add("性别");
                }else if (name.equals("startDate")){
                    header.add("开始时间");
                }else if (name.equals("endDate")){
                    header.add("结束时间");
                }else if (name.equals("sum")){
                    header.add("合计");
                }else {
                    header.add(name);
                }
                list.add(header);
            });
            return list;
        }else if (reptileType.equals("unemployment")){
            headerData.forEach((name, value) -> {
                List<String> header = new ArrayList<String>();
                if (name.equals("deptNumber")) {
                    header.add("单位编号");
                } else if (name.equals("userNumber")) {
                    header.add("个人编号");
                } else if (name.equals("userName")) {
                    header.add("姓名");
                } else if (name.equals("userIdentityCardNumber")) {
                    header.add("证件号码");
                }else if (name.equals("identityCheckDocument")){
                    header.add("失业证书");
                }else if (name.equals("identityCheckDate")){
                    header.add("失业证书发放时间");
                }else if (name.equals("sixTrue")){
                    header.add("数据有效性");
                }else if (name.equals("startDate")){
                    header.add("开始时间");
                }else if (name.equals("endDate")){
                    header.add("结束时间");
                }else if (name.equals("sum")){
                    header.add("合计");
                }else {
                    header.add(name);
                }
                list.add(header);
            });
            return list;
        }else {
            headerData.forEach((name, value) -> {
                List<String> header = new ArrayList<String>();
                if (name.equals("deptNumber")) {
                    header.add("单位编号");
                } else if (name.equals("userNumber")) {
                    header.add("个人编号");
                } else if (name.equals("userName")) {
                    header.add("姓名");
                } else if (name.equals("userIdentityCardNumber")) {
                    header.add("证件号码");
                }else if (name.equals("startDate")){
                    header.add("开始时间");
                }else if (name.equals("endDate")){
                    header.add("结束时间");
                }else if (name.equals("sum")){
                    header.add("合计");
                }else {
                    header.add(name);
                }
                list.add(header);
            });
            return list;
        }
    }

    private static List<List<String>> getData(List<Map<String, String>> dataList) {
        List<List<String>> list = new ArrayList();
        dataList.forEach(row -> {
            List<String> data = new ArrayList<String>();
            row.forEach((columnName, columnValue) -> {
                data.add(columnValue);
            });
            list.add(data);
        });
        return list;
    }


}


